/**
 * author：是三金呀
 * 微信号：junxin367
 * date：2024-11-9 20:43:57
 */

import { _decorator, Component, director, Sprite, SpriteFrame } from 'cc';
import { RankUtil } from './utils/zfb/RankUtil';
import { XinConfig } from './config/XinConfig';
const { ccclass, property } = _decorator;
const wx = window['wx'];

@ccclass('Ranking')
export class Ranking extends Component {
    @property(SpriteFrame)
    on: SpriteFrame = null;
    @property(SpriteFrame)
    off: SpriteFrame = null;

    @property(Sprite)
    m_friendSprite: Sprite = null;
    @property(Sprite)
    m_allSprite: Sprite = null;

    // 排行榜
    m_rankUtil: RankUtil = RankUtil.getInstance();

    start() {
        // 显示全国排行榜
        this.onBtnAll();
    }

    onEnable() {
        this.checkSpriteFrame("all");
    }

    update(deltaTime: number) {

    }


    /**
     * 检查并设置状态
     *
     * @param name 
     */
    checkSpriteFrame(name: "friend" | "all") {
        switch (name) {
            case "friend":
                this.m_friendSprite.spriteFrame = this.on;
                this.m_allSprite.spriteFrame = this.off;
                this.m_friendSprite.node.setSiblingIndex(1);
                this.m_allSprite.node.setSiblingIndex(0);
                break;
            case "all":
                this.m_friendSprite.spriteFrame = this.off;
                this.m_allSprite.spriteFrame = this.on;
                this.m_friendSprite.node.setSiblingIndex(0);
                this.m_allSprite.node.setSiblingIndex(1);
                break;
        }
    }

    /***************** 按钮 ******************/
    btnClose() {
        this.node.active = false
    }


    // 显示排行榜
    btnOpenRank() {
        // 优先显示全国排行榜
        this.onBtnAll();
    }

    // 好友排行榜
    async onBtnFriend() {
        this.checkSpriteFrame("friend");
        const openId = await this.getOpenId();
        this.postOpenDataMessage("event", "friendRank", openId);
    }


    // 全国排行榜
    async onBtnAll() {
        this.checkSpriteFrame("all");
        const openId = String(await this.getOpenId());
        if (openId === "TEST_OPENID") return;
        let data: any = await this.m_rankUtil.getRankList(String(openId), 0, 100);
        data.openId = openId;
        console.log("全国排行榜", data);
        this.postOpenDataMessage("event", "allRank", data);
    }


    /***************** 测试按钮 ******************/

    // 提交成绩
    async onBtnPushScore() {
        const openId = String(await this.getOpenId());
        if (openId === "TEST_OPENID") return;
        this.m_rankUtil.replaceScore(openId, {}, 100).then((res: any) => {
            console.log(res);
        }).catch((err: any) => {
            console.error(err);
        })
    }

        
    /***************** 封装函数 ******************/
    async getOpenId() {
        if (!this.isWxEnv()) {
            return new Promise((resolve, reject) => {
                console.log("TEST_OPENID");
                resolve("TEST_OPENID");
            })
        }
        const appid = XinConfig.wxConfig.appId;
        // 获取本地存储中的openid
        const openIdKey = appid + '_openid';
        return new Promise((resolve, reject) => {
            const openId: string = wx.getStorageSync(openIdKey)
            if (openId) {
                // 如果本地存储中有openid，则直接返回
                resolve(openId);
            } else {
                // 调用微信登录接口
                wx.login({
                    success(res: any) {
                        if (res.code) {
                            // 发起网络请求获取openid
                            wx.request({
                                method: 'POST',
                                url: XinConfig.wxConfig.getOpenIdUrl,
                                data: {
                                    appid: appid,
                                    js_code: res.code,
                                },
                                success(res: any) {
                                    console.log(res)
                                    if (res?.data?.openid) {
                                        // 将openid保存到本地存储中
                                        wx.setStorageSync(openIdKey, res.data.openid);
                                        // 返回openid
                                        resolve(res.data.openid);
                                    } else {
                                        resolve(null)
                                    }
                                }
                            })
                        } else {
                            resolve(null)
                        }
                    }
                })
            }
        })
    }

    // 判断是否微信环境
    isWxEnv(): boolean {
        if (typeof (wx) !== "undefined") {
            return true;
        }
        return false;
    }

    // 发送数据到子域
    postOpenDataMessage(type: string, event: string, data: any) {
        if (!this.isWxEnv()) {
            return;
        }

        let openDataContext = wx.getOpenDataContext();
        openDataContext.postMessage({
            type: type,
            event: event,
            data: data,
        });
    }

}


